package com.tsvetanv.data.binding.property.editors.supported;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import junit.framework.TestCase;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.ServletRequestDataBinder;

import com.tsvetanv.data.binding.model.property.editors.supported.ThreeDatesCommandBean;

public class ThreeDatesCommandBeanBindTest extends TestCase {
	ThreeDatesCommandBean bean;
	ServletRequestDataBinder binder;
	MockHttpServletRequest request;

	@Override
	protected void setUp() throws Exception {
		bean = new ThreeDatesCommandBean();
		binder = new ServletRequestDataBinder(bean, "beanName");
		request = new MockHttpServletRequest();
	}

	public void testThreeDatesCommandBeanBind() throws Exception {
		SimpleDateFormat firstDateFormat = new SimpleDateFormat("dd-MM-yyyy");
		SimpleDateFormat secondDateFormat = new SimpleDateFormat("dd.MM.yyyy");
		SimpleDateFormat thirdDateFormat = new SimpleDateFormat("dd:MM:yyyy");

		CustomDateEditor firstDateEditor = new CustomDateEditor(
				firstDateFormat, true);
		CustomDateEditor secondDateEditor = new CustomDateEditor(
				secondDateFormat, true);
		CustomDateEditor thirdDateEditor = new CustomDateEditor(
				thirdDateFormat, true);

		binder.registerCustomEditor(Date.class, firstDateEditor);
		binder.registerCustomEditor(Date.class, "secondDate", secondDateEditor);
		binder.registerCustomEditor(Date.class, "thirdDate", thirdDateEditor);

		request.addParameter("firstDate", "20-11-2011");
		request.addParameter("secondDate", "20.11.2011");
		request.addParameter("thirdDate", "20:11:2011");

		binder.bind(request);

		Date expectedFirstDate = firstDateFormat.parse("20-11-2011");
		Date expectedSecondDate = secondDateFormat.parse("20.11.2011");
		Date expectedThirdDate = thirdDateFormat.parse("20:11:2011");

		assertEquals(expectedFirstDate, bean.getFirstDate());
		assertEquals(expectedSecondDate, bean.getSecondDate());
		assertEquals(expectedThirdDate, bean.getThirdDate());

	}
}
